﻿using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Vision.Abstractions.Processing;
using Vision.Abstractions;

namespace Vision.Processing
{
    /// <summary>
    /// 基于OpenCV的图像处理器实现
    /// </summary>
    public class OpenCvImageProcessor : IImageProcessor
    {
        /// <summary>
        /// 处理图像帧
        /// </summary>
        public CameraFrameMessage ProcessFrame(CameraFrameMessage frame, double binaryThreshold, double edgeThreshold)
        {
            try
            {
                // 创建空的 Mat 并填充数据
                using var sourceMat = new Mat(frame.Height, frame.Width, MatType.CV_8UC1);
                System.Runtime.InteropServices.Marshal.Copy(frame.ImageData, 0, sourceMat.Data, frame.ImageData.Length);

                // 创建输出Mat
                using var processedMat = new Mat();

                // 应用二值化
                using var binaryMat = new Mat();
                Cv2.Threshold(sourceMat, binaryMat, binaryThreshold, 255, ThresholdTypes.Binary);

                // 应用边缘检测 (Canny)
                Cv2.Canny(binaryMat, processedMat, edgeThreshold, edgeThreshold * 2);

                // 将处理结果转换为byte数组
                var processedData = new byte[processedMat.Total() * processedMat.ElemSize()];
                System.Runtime.InteropServices.Marshal.Copy(processedMat.Data, processedData, 0, processedData.Length);


                // 创建新的CameraFrameMessage
                return new CameraFrameMessage
                (
                     processedData,
                      frame.Width,
                      frame.Height
                );
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"图像处理错误: {ex.Message}");
                // 如果处理失败，返回原图像
                return frame;
            }
        }
    }
}
